package com.loong.web.gp4j.component.intercept;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.loong.tool.lang.Strings;
import com.loong.tool.secret.base.Base64;
import com.loong.tool.secret.base.UTF8;
import com.loong.web.gp4j.bean.schema.error.Errors;
import com.loong.web.gp4j.service.error.ErrorService;
import com.loong.web.suppert.exception.PublishException;
import com.loong.web.suppert.intercept.auth.UnAuthHandler;

/**
 * 无权限访问代理组件
 *
 * @author 张成轩
 */
public class AuthComponent implements UnAuthHandler {

	@Resource
	private ErrorService errorService;

	/** 登录跳转路径参数名 */
	private static final String ATTR_BACK = "back";
	/** 登录路径 */
	private static final String LOGIN_PATH = "/login/";

	@Override
	public void mapping(HttpServletRequest request, HttpServletResponse response, boolean hasUser) throws IOException {

		if (hasUser) {
			errorService.error(request, Errors.UNAUTH);
			response.sendRedirect(request.getContextPath() + "/");
		} else {
			String back = request.getServletPath();
			if (request.getQueryString() != null)
				back += ('?' + request.getQueryString());
			response.sendRedirect(Strings.concat(request.getContextPath(), LOGIN_PATH, "?", ATTR_BACK, "=",
					Base64.encode(UTF8.getBytes(back))));
		}
	}

	@Override
	public void api(HttpServletRequest request, HttpServletResponse response, boolean hasUser) throws IOException {

		if (hasUser) {
			errorService.error(request, Errors.UNAUTH);
			throw new PublishException("无访问权限");
		} else
			throw new PublishException("尚未登录，请登录后重试！");
	}
}
